package DAO;

import POJO.Master;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class MasterDAO extends DAO<Master>{

    public MasterDAO(Connection c){
        super(c);
    }

    @Override
    public Master create(Master obj) {
    	PreparedStatement prep = null;
        Master m = null;
		ResultSet result = null;
    	try{
            prep = this.prepare("INSERT INTO Master (Master_ID, nom_master)" +
				" VALUES (nextval('master_master_id_seq'), " + obj.getNom() + ")");
            prep.execute();  
            prep = prepare("SELECT currval('master_master_id_seq') as id");
            if(prep.execute()){
              result = prep.getResultSet();
            }
 			while(result.next()){
 				long id = result.getLong("id");
 				m = obj; m.setId(id);
 			}
    	} catch (SQLException sqle){
    		sqle.printStackTrace();
    	}finally{
            try{
                if(prep!=null){
                    prep.close();
                }
            }catch(SQLException ex){
                ex.printStackTrace();
            }
        }
    	return m;
    }
    
    @Override
    public boolean update(Master obj) {
        PreparedStatement prep = null;
        boolean res = false;
       	try{
            prep = this.prepare("UPDATE Master SET nom= ? where master_id= ?;");
            prep.setString(1,obj.getNom());
            prep.setLong(2,obj.getId());
            prep.execute();
            res = true;
    	} catch (SQLException sqle){
    		sqle.printStackTrace();
    	}finally{
            try{
                if(prep!=null){
                    prep.close();
                }
            }catch(SQLException e){
                e.printStackTrace();
            }
        }
        return res;
    }

    @Override
    public boolean delete(Master obj) {
    	PreparedStatement prep = null;
        boolean res = false;
        try{
            prep = prepare("DELETE FROM Master " +
                                "WHERE Master_id= " + obj.getId());
            prep.execute();
            res = true;
        } catch (SQLException sqle){
            sqle.printStackTrace();
        }finally{
            try{
                if(prep!=null){
                    prep.close();
                }
            }catch(SQLException e){
               e.printStackTrace();
            }
        }
        return res;
    }

    @Override
    public ResultSet find(long id) {
        try{
            PreparedStatement prep = prepare("SELECT Master_ID, Nom_Master FROM Master" +
                                                    " WHERE Master_ID = ?;");
            prep.setLong(1, id);
            if(prep.execute()){
                return prep.getResultSet();
            }
        } catch (SQLException sqle){
            sqle.printStackTrace();
        }
        return null;
    }
}
